package chagine.core.util;


import chagine.core.ErrorCode;
import chagine.core.exception.SeeingException;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;

/**
 * com.seeing.core.util.NetworkUtil
 * Created by 张正伟（zzw）on 2018/4/24.
 */
public class NetworkUtil {

    private NetworkUtil() {
    }

    public static String getHostIp() throws SeeingException {
        String machineIp = null;
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
                for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                    InetAddress inetAddress = interfaceAddress.getAddress();
                    if (inetAddress.isLinkLocalAddress() || inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress()) {
                        continue;
                    }
                    machineIp = inetAddress.getHostAddress();
                    break;
                }
            }
        } catch (Exception e) {
            throw new SeeingException(ErrorCode.RUNNING_EXCEPTION, "获取本机器ip时候发生错误" + e.getMessage());
        }
        return machineIp;
    }

    public static String getMAC() throws SeeingException {
        String mac = null;
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
                for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                    InetAddress inetAddress = interfaceAddress.getAddress();
                    if (inetAddress.isLinkLocalAddress() || inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress()) {
                        continue;
                    }

                    byte[] macBytes = networkInterface.getHardwareAddress();
                    if (macBytes == null) {
                        continue;
                    }
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < macBytes.length; i++) {
                        sb.append(String.format("%02X%s", macBytes[i], i < macBytes.length - 1 ? "-" : ""));
                    }
                    mac = sb.toString();
                    break;
                }
            }
        } catch (Exception e) {
            throw new SeeingException(ErrorCode.RUNNING_EXCEPTION, "获取本机器ip时候发生错误" + e.getMessage());
        }
        return mac;
    }
}
